/**
 * Copyright 2011 Christian Padovano
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package it.sijom.converters;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.commons.beanutils.Converter;

import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl;

/**
 * Converte un Date in un oggetto di tipo javax.xml.datatype.XMLGregorianCalendar utile ai WS
 * oppure converte una data in formato stringa (dd/MM/yyyy) in formato javax.xml.datatype.XMLGregorianCalendar
 * @author c.padovano
 *
 */
public  class  XmlCalendarConverter implements Converter {
	
	private String _datePattern;
	
	public XmlCalendarConverter(String datePattern) {
		this._datePattern = datePattern;
	}

	@Override
	public Object convert(Class target, Object value) {
		Object _dummyValue = value instanceof PatternProxy ? ((PatternProxy)value).getValue() : value;
		//questo caso va ignorato...
		if (target.getName().equals("java.util.Date")) {
			if (_dummyValue instanceof XMLGregorianCalendar) {
				return getDateFromXmlGregorianCalendar((XMLGregorianCalendar) _dummyValue);
			} else if (value instanceof PatternProxy && _dummyValue instanceof String && !"[unassigned]".equals(_dummyValue)) {
				return stringToDate((String)_dummyValue,((PatternProxy)value).getPattern());
			} else if (_dummyValue instanceof String){
				return stringToDate((String)_dummyValue,_datePattern);
			} else {
			    return value;
			}
		} else if (value instanceof Date) {
			return getXmlGregorianCalendarFromDate((Date) value);
		} else if (value instanceof String) {
			return getXmlGregorianCalendarFromDate((String) value);
		} else if (value instanceof XMLGregorianCalendar) {
			return getDateFromXmlGregorianCalendar((XMLGregorianCalendar) value);
		}
		return null;
	}
	
	private XMLGregorianCalendar getXmlGregorianCalendarFromDate(Date date){

		Calendar c = Calendar.getInstance();
		c.setTime(date);

		XMLGregorianCalendar xD = new XMLGregorianCalendarImpl();
		
		xD.setDay(c.get(Calendar.DAY_OF_MONTH));
		xD.setYear(c.get(Calendar.YEAR));
		xD.setMonth(c.get(Calendar.MONTH)+1);
		xD.setHour(c.get(Calendar.HOUR_OF_DAY));
		xD.setMinute(c.get(Calendar.MINUTE));
		xD.setSecond(c.get(Calendar.SECOND));
		return xD;
	}
	
	/**
	 * dd/Mm/yyyy
	 * @param data
	 * @return
	 */
	private  XMLGregorianCalendar getXmlGregorianCalendarFromDate(String data){
		String[] datasplit =data.split("/");
		

		XMLGregorianCalendar xD = new XMLGregorianCalendarImpl();
		
		xD.setDay(Integer.parseInt(datasplit[0]));
		xD.setMonth(Integer.parseInt(datasplit[1]));
		xD.setYear(Integer.parseInt(datasplit[2]));
		xD.setHour(0);
		xD.setMinute(0);
		xD.setSecond(0);
		return xD;
	}
	
	/**
	 * converte un XMLGregorianCalendar in java.util.Date ignorando l'ora
	 * @param xmlDate data da convertire
	 * @return orario convertito in Date
	 */
	public static Date getDateFromXmlGregorianCalendarNoTime(XMLGregorianCalendar xmlDate){
		Date dt = null;
		XMLGregorianCalendar xD = xmlDate;
		Calendar c = Calendar.getInstance();
 		c.set(xD.getYear(), xD.getMonth()-1,xD.getDay(), 0, 0,0);
		dt = c.getTime();
		return dt;
	}
	
	private  Date getDateFromXmlGregorianCalendar(XMLGregorianCalendar xmlDate){
		Date dt = null;
		XMLGregorianCalendar xD = xmlDate;
		Calendar c = Calendar.getInstance();
//		c.set(xD.getYear(), xD.getMonth()-1,xD.getDay(), xD.getHour(), xD.getMinute(),xD.getSecond());
		c.set(xD.getYear(), xD.getMonth()-1,xD.getDay());
		dt = c.getTime();
		return dt;
	}
	
	private  Date stringToDate(String date, String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		Date dataConvertita = null;
		try {
			dataConvertita = formatter.parse(date);
		}
		catch (ParseException e) {
			System.out.println("ERRORE stringToDate" + e.getMessage());
		}
		return dataConvertita;
	}
	
	
	
}